package com.jingdianjichi.util;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

import java.util.Map;

public class HttpUtil {

    private static final int DEFAULT_TIMEOUT_MS = 5000;

    // GET 请求（无参）
    public static String get(String url) {
        return get(url, null, DEFAULT_TIMEOUT_MS);
    }

    // GET 请求（带查询参数）
    public static String get(String url, Map<String, Object> params) {
        return get(url, params, DEFAULT_TIMEOUT_MS);
    }

    // GET 请求（带查询参数和超时）
    public static String get(String url, Map<String, Object> params, int timeoutMs) {
        try {
            String finalUrl = MapUtil.isNotEmpty(params)
                    ? cn.hutool.http.HttpUtil.urlWithForm(url, params, CharsetUtil.CHARSET_UTF_8, true)
                    : url;
            HttpRequest req = cn.hutool.http.HttpUtil.createGet(finalUrl).timeout(timeoutMs);
            try (HttpResponse resp = req.execute()) {
                if (resp.isOk()) {
                    return resp.body();
                }
                throw new HttpException("HTTP GET failed, status=" + resp.getStatus());
            }
        } catch (Exception e) {
            throw new RuntimeException("HTTP GET request error: " + e.getMessage(), e);
        }
    }

    // POST JSON（便于后续扩展使用）
    public static String postJson(String url, String json) {
        return postJson(url, json, DEFAULT_TIMEOUT_MS);
    }

    public static String postJson(String url, String json, int timeoutMs) {
        try {
            try (HttpResponse resp = cn.hutool.http.HttpUtil.createPost(url)
                    .timeout(timeoutMs)
                    .header("Content-Type", "application/json;charset=utf-8")
                    .body(StrUtil.utf8Bytes(StrUtil.blankToDefault(json, "{}")))
                    .execute()) {
                if (resp.isOk()) {
                    return resp.body();
                }
                throw new HttpException("HTTP POST JSON failed, status=" + resp.getStatus());
            }
        } catch (Exception e) {
            throw new RuntimeException("HTTP POST JSON request error: " + e.getMessage(), e);
        }
    }
}
